/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package SynchronizationLayer;

import java.util.concurrent.PriorityBlockingQueue;
import org.joda.time.DateTime;

/**
 *
 * @author Tomasz Nowak
 */
public class TimeoutQueue implements Runnable
{
	private PriorityBlockingQueue<ConversationTimeout> queue;
	static TimeoutQueue instance;
	Thread queueThread;

	private TimeoutQueue()
	{
		queue = new PriorityBlockingQueue<>();
	}

	public static TimeoutQueue getInstance()
	{
		if ( instance == null )
		{
			instance = new TimeoutQueue();
		}
		return instance;
	}

	public void enqueue( ConversationTimeout timeout )
	{
		queue.add(timeout);
	}

	@Override
	public void run()
	{
		queueThread = Thread.currentThread();
		while ( true )
		{
			ConversationTimeout timeout = queue.peek();
			if ( timeout == null )
			{
				try
				{
					Thread.sleep(1000);
				}
				catch ( InterruptedException ex )
				{
					continue;
				}
				continue;
			}
			long millis = timeout.timeout.getMillis() - DateTime.now().getMillis();

			if ( millis <= 0 )
			{
				timeout.conversation.raiseTimeoutHandler();
				queue.remove(timeout);
				//wykonac
			}
			else
			{
				try
				{
					Thread.sleep(millis);
				}
				catch ( InterruptedException ex )
				{
					continue;
				}
			}
		}
	}
}
